var app = getApp();
var utils = require("../../utils/util.js");

Page({
  data: {
    publicUrl:"",
    musicList:[],
    musicTitle:"",
    musicDesc:"",
    musicImg:"",
    poster: "",
    name: "",
    author: "",
    src: "",
    playing:false
  },

  onLoad: function (options) {
    // 在此进入程序是，判断playing的状态
    if (app.globalData.backgroundAudioPlaying){
      this.setData({
        playing:true,
        name:app.globalData.musicName
      })
    }

    // 监听音乐播放停止
    wx.onBackgroundAudioStop(function(){
      console.log("音乐播放完成，下一曲播放")
    })

    var publicUrl = "";
    var baseUrl = app.globalData.musicUrl;
    switch(options.type){
      case "今日推荐":
        publicUrl = baseUrl + "/sxtstu/music/baidu/list.php?type=24&count=15&offset=0"
        break;
      case "朋友圈":
        publicUrl = baseUrl + "/sxtstu/music/baidu/list.php?type=25&count=15&offset=0"
        break;
      case "热歌榜":
        publicUrl = baseUrl + "/sxtstu/music/baidu/list.php?type=2&count=15&offset=0"
        break;
      case "新歌榜":
        publicUrl = baseUrl + "/sxtstu/music/baidu/list.php?type=1&count=15&offset=0"
        break;
      case "摇滚榜":
        publicUrl = baseUrl + "/sxtstu/music/baidu/list.php?type=11&count=15&offset=0"
        break;
    }
    this.setData({
      publicUrl: publicUrl
    })
    utils.http(publicUrl, this.getMusicList,null,null)
  },
  getMusicList:function(data){
    this.setData({
      musicList: data.song_list,
      musicTitle: data.billboard.name,
      musicDesc: data.billboard.comment,
      musicImg: data.billboard.pic_s192
    })
  },

  // 播放事件
  playMusicHandler:function(event){
    // 获取播放资源
    var musicid = event.currentTarget.dataset.musicid;
    utils.http(app.globalData.musicUrl + "/sxtstu/music/baidu/play.php?mid=" +musicid,this.getPlayMusic,null,null)
  },

  // 播放数据获取
  getPlayMusic:function(data){
    console.log(data)
    var temp = {
      poster: data.songinfo.pic_big,
      name: data.songinfo.title,
      author: data.songinfo.author,
      src: data.bitrate.show_link
    }
    this.setData(temp);
    this.play();
  },

  // 播放功能
  play:function(){
    var that = this;
    wx.playBackgroundAudio({
      dataUrl: this.data.src,
      title: this.data.name,
      coverImgUrl: this.data.poster,
      complete:function(){
        that.setData({
          playing: true
        })
      }
    })
    app.globalData.backgroundAudioPlaying = true;
    app.globalData.musicName = this.data.name;

    // wx.seekBackgroundAudio({
    //   position: 180
    // })
  },

  // 暂停播放
  pause:function(){
    wx.pauseBackgroundAudio();
    this.setData({
      playing: false
    })
    app.globalData.backgroundAudioPlaying = false;
  },

  // 停止播放
  stop:function(){
    wx.stopBackgroundAudio();
    this.setData({
      playing: false
    })
    app.globalData.backgroundAudioPlaying = false;
  }
})